package com.pubinfo.passbook.data.quartz.service.impl;

import com.pubinfo.passbook.common.service.master.TAutoTaskService;
import com.pubinfo.passbook.data.quartz.service.TaskService;
import com.pubinfo.passbook.data.quartz.utils.QuartzManager;
import com.pubinfo.passbook.common.entity.TAutoTask;
import com.pubinfo.passbook.common.model.constant.TaskStatusEnum;
import lombok.SneakyThrows;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {
  
  @Resource
  TAutoTaskService tAutoTaskService;
  @Autowired
  QuartzManager quartzManager;
  
  @SneakyThrows
  @Override
  public void run(TAutoTask task) {
    quartzManager.runJobNow(task);
  }
  
  @SneakyThrows
  @Override
  // @RequiredLog("禁用启用任务")//
  public Boolean changeStatus(String jobId) {
    TAutoTask autoJob = tAutoTaskService.getById(jobId);
    if (autoJob == null) {
      return false;
    }
    //  String status =  ;
    if (!TaskStatusEnum.STOP.getCode().equals(autoJob.getStatus())) {
      quartzManager.deleteJob(autoJob);
      autoJob.setStatus(TaskStatusEnum.STOP.getCode());
    } else {
      autoJob.setStatus(TaskStatusEnum.RUNNING.getCode());
      quartzManager.addJob(autoJob);
    }
    return tAutoTaskService.updateById(autoJob);
  }
  
  @SneakyThrows
  @Override
  public Boolean removeBatch(String[] ids) {
    for (String id : ids) {
      TAutoTask task = tAutoTaskService.getById(id);
      quartzManager.deleteJob(task);
    }
    
    return tAutoTaskService.removeByIds(Arrays.asList(ids));
  }
  
  @Override
  public void initSchedule() throws SchedulerException {
    List<TAutoTask> taskList = tAutoTaskService.list();
    for (TAutoTask task : taskList) {
      if (TaskStatusEnum.RUNNING.getCode().equals(task.getStatus())) {
        quartzManager.addJob(task);
      }
    }
  }
}
